import java.math.BigDecimal;

/**
 * @Author: DengJia
 * @Date: 2021/9/14 16:05
 * @Description: 浮点数之间的等值判断
 */

public class Main {
    public static void main(String[] args) {
        // floatValueCompare();

    }

    static void floatValueCompare() {
        /* 1、不可用 ==、equals 判断 */
        float a1 = 1.0f, a2 = 0.9f, a3 = 0.8f;
        float v1 = a1 - a2, v2 = a2 - a3;
        System.out.println(v1 == v2); // false
        System.out.println(Float.valueOf(v1).equals(v2)); // false

        /* 2、小于指定的一个误差范围视为相等 */
        float diff = 1e-6f; // 设定一个误差范围
        System.out.println(Math.abs(v1 - v2) < diff); // true

        /* 3、使用 BigDecimal 定义浮点值，再进行比较 */
        BigDecimal b1 = new BigDecimal("1.0"), b2 = new BigDecimal(".9"), b3 = new BigDecimal(".8");
        BigDecimal s1 = b1.subtract(b2), s2 = b2.subtract(b3);
        System.out.println(s1.compareTo(s2) == 0); // true

        BigDecimal d1 = new BigDecimal("1.0");
        BigDecimal d2 = new BigDecimal("1.00");
        System.out.println(d1.compareTo(d2) == 0);
        System.out.println(d1.equals(d2));
    }
}
